const express = require('express');
const multiparty = require('connect-multiparty');
const multipartMiddleware = multiparty();
const admin = express();
const fs = require('fs');
const path = require('path');
const http = require('http');
// const https = require('https');
// const url = require('url');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const OssHelper = require('../util/OSSHelper');
OssHelper.init(require('../config').oss);
// const privateKey = fs.readFileSync('../cert/ppt//215093671130336.key');
// const certificate = fs.readFileSync('../cert/ppt/215093671130336.pem');
// const credentials = {key: privateKey, cert: certificate};

const httpServer = http.createServer(admin);
// const httpsServer = https.createServer(credentials, admin);
const PORT = 80;
// const SSLPORT = 443;

admin.use(express.static(path.join(__dirname, '../public')));
admin.use(bodyParser.json());
admin.use(bodyParser.urlencoded({extended: false}));

httpServer.listen(PORT, function () {
    console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
// httpsServer.listen(SSLPORT, function () {
//     console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
// });

admin.all('*', function (req, res, next) {
    console.log('req ', req.query, req.body, req.path);
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    res.data = function (data) {
        this.json({code: 200, data: data});
    };
    next();
});
// Welcome
admin.get('/', function (req, res) {
    if (req.protocol === 'https') {
        res.status(200).send('Welcome to Safety Land!');
    }
    else {
        res.status(200).send('Welcome!');
    }
});
require('../db/mongodb').load();

admin.get('/admin/ajax',async function(req,res,next){
    let time = Date.now();
    let router = req.query.router;
    try{
        const AdminModel=mongoose.models['Admin'];
        let user=await AdminModel.findOne({loginId:req.query.loginId,token:req.query.token});
        if(!user){
            throw new Error('用户登陆验证失败');
        }
        req.query.self=user;
        let routers=req.query.router.split('.');
        let returnData=undefined;
        switch(routers.length){
            case 1:{
                returnData=await user[routers[0]](req.query);
                break;
            }
            case 2:{
                returnData=await user[routers[0]][routers[1]](req.query);
                break;
            }
            case 3:{
                returnData=await user[routers[0]][routers[1]][routers[2]](req.query);
                break;
            }
            case 4:{
                returnData=await user[routers[0]][routers[1]][routers[2]][routers[3]](req.query);
                break;
            }
        }
        await user.save();
        if(req.query.router.includes('Excel')){
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            let userAgent = (req.headers['user-agent']||'').toLowerCase();
            let fileName = `${req.query.name}(${returnData.addDate}).xlsx`;
            if(userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
                res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(fileName));
            } else if(userAgent.indexOf('firefox') >= 0) {
                res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileName)+'"');
            } else {
                /* safari等其他非主流浏览器只能自求多福了 */
                res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(fileName).toString('binary'));
            }
            res.end(returnData.result, 'binary');
            console.log(router, "<==router Excel time =",  Date.now() - time);
        }else{
            res.data(returnData);
        }
        console.log(router, "<==router time =",  Date.now() - time);
    }catch(e){
        console.error(router, Date.now() - time, "<==router error: ", e);
        next(e.message);
    }
});

admin.post('/admin/ajax',async function(req,res,next){
    try{
        const AdminModel=mongoose.models['Admin'];
        let user=await AdminModel.findOne({loginId:req.body.loginId,token:req.body.token});
        if(!user){
            throw new Error('用户登陆验证失败');
        }
        req.body.self=user;
        let routers=req.body.router.split('.');
        let returnData=undefined;
        switch(routers.length){
            case 1:{
                returnData=await user[routers[0]](req.body);
                break;
            }
            case 2:{
                returnData=await user[routers[0]][routers[1]](req.body);
                break;
            }
            case 3:{
                returnData=await user[routers[0]][routers[1]][routers[2]](req.body);
                break;
            }
            case 4:{
                returnData=await user[routers[0]][routers[1]][routers[2]][routers[3]](req.body);
                break;
            }
        }
        await user.save();
        res.data(returnData);
    }catch(e){
        console.log(e);
        next(e.message);
    }
});
// 拦截用户必须登陆才能访问其他路由

require('../db/default/registerDefaultAdmin');
// 检查登录
admin.post("/admin/checkLogin", async function (req, res) {
    let loginId = !!req.body.loginId ? req.body.loginId : '';
    let password = !!req.body.password ? req.body.password : '';
    let AdminModel = mongoose.models['Admin'];
    let checkLoginRes = await AdminModel.checkLogin(loginId, password);
    // console.log('checkLoginRes = ', checkLoginRes);
    let result = {};
    if (checkLoginRes) {
        result = Object.assign({code: 200, msg: '管理员登录成功', data: checkLoginRes});
    } else {
        result = Object.assign({code: 500, msg: '用户名或密码错误', data: checkLoginRes});
    }

    res.json(result);
});

admin.post("/channel/checkLogin", async function (req, res,next) {
    let loginId = !!req.body.loginId ? req.body.loginId : '';
    let loginPass = !!req.body.loginPass ? req.body.loginPass : '';
    let ChannelModel = mongoose.models['Channel'];
    let channel=await ChannelModel.checkLogin(loginId,loginPass);
    if (!!channel) {
        return res.json({code:200,data:channel});
    } else {
        next('登陆用户名/密码错误');
    }
});
admin.get('/channel/ajax',async function(req,res,next){
    try{
        const ChannelModel=mongoose.models['Channel'];
        let user=await ChannelModel.findOne({loginId:req.query.loginId,loginPass:req.query.loginPass});
        if(!user){
            throw new Error('用户登陆验证失败');
        }
        req.query.self=user;
        let routers=req.query.router.split('.');
        let returnData=undefined;
        switch(routers.length){
            case 1:{
                returnData=await user[routers[0]](req.query);
                break;
            }
            case 2:{
                returnData=await user[routers[0]][routers[1]](req.query);
                break;
            }
            case 3:{
                returnData=await user[routers[0]][routers[1]][routers[2]](req.query);
                break;
            }
            case 4:{
                returnData=await user[routers[0]][routers[1]][routers[2]][routers[3]](req.query);
                break;
            }
        }
        await user.save();
        res.data(returnData);
    }catch(e){
        console.log(e);
        next(e.message);
    }
});
admin.post('/channel/ajax',async function(req,res,next){
    try{
        const ChannelModel=mongoose.models['Channel'];
        let user=await ChannelModel.findOne({loginId:req.body.loginId,loginPass:req.body.loginPass});
        if(!user){
            throw new Error('用户登陆验证失败');
        }
        req.body.self=user;
        let routers=req.body.router.split('.');
        let returnData=undefined;
        switch(routers.length){
            case 1:{
                returnData=await user[routers[0]](req.body);
                break;
            }
            case 2:{
                returnData=await user[routers[0]][routers[1]](req.body);
                break;
            }
            case 3:{
                returnData=await user[routers[0]][routers[1]][routers[2]](req.body);
                break;
            }
            case 4:{
                returnData=await user[routers[0]][routers[1]][routers[2]][routers[3]](req.body);
                break;
            }
        }
        await user.save();
        res.data(returnData);
    }catch(e){
        console.log(e);
        next(e.message);
    }
});

admin.use(multiparty({uploadDir:'./public/upload' }));

admin.post('/upload', multipartMiddleware, async function (req, res) {
    console.log('上传文件', req.body, req.files);
    let path = req.files['imgFiles'][0].path;
    let fileName = path.substring(path.indexOf('upload') + 7);
    let imgUrl = await OssHelper.upload(path, fileName);

    let source = fs.createReadStream(path);
    let dest = fs.createWriteStream('./public/upload/' + fileName);
    source.pipe(dest);
    source.on('end', function() { fs.unlinkSync(path);});   //delete
    source.on('error', function(err) {  });

    console.log(imgUrl, 'imgUrl');
    res.json([{error: 0, url: imgUrl}]);
});


admin.use(function (err, req, res, next) {
    res.json({code: 500, msg: err});
});
admin.use(function (req, res, next) {
    res.json({code: 500, msg: 'no such router'});
});
